package com.mega.ebcs.service;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mega.ebcs.entity.EbcsFormat;
import com.mega.ebcs.entity.EbcsFormatId;
import com.mega.ebcs.entity.EbcsTransType;

@Service("ebcsService") @Transactional
public class EbcsServiceImpl implements EbcsService{

	@Autowired private SessionFactory sessionFactory;
	
	@SuppressWarnings("rawtypes")
	@Override
	public List<EbcsFormat> findEbcsFormatByEbcsTransType(Long ebcsTransType, String exchangeType) {
		List recs = sessionFactory.getCurrentSession()
				.createQuery("select ebcsFormat from EbcsFormat ebcsFormat join ebcsFormat.ebcsTransType where ebcsFormat.ebcsTransType.id = :ebcsTransType and ebcsFormat.ebcsFormatId.exchangeType =:exchangeType order by CAST(ebcsFormat.ebcsFormatId.id AS integer)")
				.setCacheable(true)
				.setParameter("ebcsTransType", ebcsTransType)
				.setParameter("exchangeType", exchangeType)
				.list();
		return  recs;
	}
	
	@Override
	public Long getTotalLengthByEbcsTransType(Long ebcsTransType, String exchangeType) {
		Long length = (Long) sessionFactory.getCurrentSession().createQuery("select sum(ebcsFormat.length) from EbcsFormat ebcsFormat join ebcsFormat.ebcsTransType where ebcsFormat.ebcsTransType.id =:ebcsTransType and ebcsFormat.ebcsFormatId.exchangeType =:exchangeType")
		.setCacheable(true)
		.setParameter("ebcsTransType", ebcsTransType)
		.setParameter("exchangeType", exchangeType).uniqueResult();
		if (length == null)
			return new Long(0);
		return length;
	}
	
	@Override
	public EbcsFormat findEbcsFormatById(EbcsFormatId id) {
		return (EbcsFormat) sessionFactory.getCurrentSession().get(EbcsFormat.class, id);
	}

	@Override
	public void saveEbcsFormat(EbcsFormat ebcsFormat) {
		sessionFactory.getCurrentSession().save(ebcsFormat);
		
	}
	
	@Override
	public EbcsTransType findEbcsTransTypeById(Long id) {
		return (EbcsTransType) sessionFactory.getCurrentSession().get(EbcsTransType.class, id);
	}

	@Override
	public void saveEbcsTransType(EbcsTransType ebcsTransType) {
		sessionFactory.getCurrentSession().save(ebcsTransType);
		
	}
}
